package util;


import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

import java.io.IOException;
import java.util.Map;

/**
 * Created by Bowen on 2014/10/27.
 */
public class JsonUtil {

    private static Logger logger = Logger.getLogger(JsonUtil.class);


    public static String writeValueAsString(Object o) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(o);
        } catch (IOException e) {
            logger.error("json序列化错误", e);
        }
        return null;
    }

    public static <T> T readObject(String json, Class<T> clazz) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.disable(org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
        try {
            return objectMapper.readValue(json, clazz);
        } catch (IOException e) {
            logger.error("json反序列化错误", e);
        }
        return null;
    }

    public static <T> T readObject(String json, TypeReference<?> typeReference) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        return (T) (typeReference.getType().equals(String.class) ? json : objectMapper.readValue(json, typeReference));
    }

    public static String requestParameter(String name,String password,String method,Map<String,Object> parameterMap) throws IOException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name",name);
        jsonObject.put("password",password);
        jsonObject.put("method",method);
        jsonObject.put("equipm_id","洒水车");
        return jsonObject.toString();
    }
}